//引入附件上传插件
var multer = require('multer');
//引入文件夹创建服务
var mkdir = require('../dao/mkdir');
//引入path
var path = require('path');

//关于multer插件的相应用法
//网址：https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md

//控制文件存储
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    //获取存储路径
    let url = req.body.url;
    //创建相应文件路径
    mkdir.mkdir('../data/'+url,err=>{
      if(err){
        console.log(err);
      }
    });
    // console.log(file);
    cb(null, path.join(__dirname,'../data/'+url));
  },
  filename: function (req, file, cb) {
    let name = req.body.name;
    //正则匹配后缀名
    let type = file.originalname.replace(/.+\./,'.');
    cb(null,name+type);
  }
});

var upload = multer({storage: storage});

module.exports = function(app){
  //前端文件上传
  app.post('/files/upload',upload.array('file',10),(req,res,next)=>{
    let url = req.body.url;
    let name = req.files[0].filename;
    req.files.imgurls = "/"+url+'/'+name;
    //获取文件信息
    res.send(req.files);
  });
}
